package com.haohan.jingyuan.wrapper;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName GwHttpServletRequestWrapper
 */
public class GwHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final String requestBody;

    public GwHttpServletRequestWrapper(HttpServletRequest request, String requestBody) {
        super(request);
        this.requestBody = requestBody;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (requestBody == null) {
            return super.getInputStream();
        }

        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                requestBody.getBytes(StandardCharsets.UTF_8));

        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return byteArrayInputStream.available() == 0;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                // 不需要实现
            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public int getContentLength() {
        return requestBody != null ? requestBody.getBytes(StandardCharsets.UTF_8).length : super.getContentLength();
    }

    @Override
    public long getContentLengthLong() {
        return requestBody != null ? requestBody.getBytes(StandardCharsets.UTF_8).length : super.getContentLengthLong();
    }
}
